﻿$('#nav li').eq(0).addClass('active');
var nowDate = getUrlId().split('-');
$('#thisDay').html('填表日期：' + nowDate[0] + '年' + nowDate[1] + '月' + nowDate[2] + '日');

var now = new Date();
var y = now.getFullYear();
var m = now.getMonth() + 1;
var d = now.getDate();
var today = new Date(y + '/' + m + '/' + d);
var urlDay = new Date(nowDate[0] + '/' + nowDate[1] + '/' + nowDate[2]);
if (urlDay.getTime() !== today.getTime()) {
  $('#submit').remove();
}

var selectWidth = '100%';
var allBrand = [];
var allProject = [];
var edit = false;
loading.show();
var b = new Vue({
  el: '#form',
  data: {
    hours: setDayHours(),
    form: {
      value: ''
    },
    days: [],
    dayForm: resetDayForm()
  },
  methods: {
    add: function () {
      if ((greatThan8(b.days) + b.dayForm.cost) > 8) {
        alert('花费时间总计不能超过8小时！');
        return false;
      }
      var validator = new Validator();

      validator.add(b.dayForm.name, [{
        strategy: 'isNonEmpty',
        errorMsg: '项目不能为空'
      }]);

      validator.add(b.dayForm.cost, [{
        strategy: 'isNonEmpty',
        errorMsg: '花费时间不能为空'
      }]);

      var errmsg = validator.start();
      if (errmsg) {
        alert(errmsg);
        return false;
      }


      b.days.push({
        projectID: b.dayForm.projectID,
        name: b.dayForm.name,
        detail: b.dayForm.detail,
        result: b.dayForm.result,
        cost: b.dayForm.cost
      });

      var id = b.dayForm.projectID;

      setTimeout(function () {
        var i = b.days.length - 1;
        var brand = getBrand();
        eachProjectId(b.days, i, 'name', function (i, id) {
          var v = getProjectName(id);
          var h = setProjects(v);
          if (v) {
            $('#selectBrand' + i).html(brand).select2().val(v.BrandName).trigger('change').next().css('width', selectWidth);
            $('#selectProject' + i).html(h).select2().val(id).trigger('change').next().css('width', selectWidth);
          }

        });

        b.dayForm = resetDayForm();
        $('#selectBrandForm').html(brand).select2().next().css('width', selectWidth);
        $('#selectProjectFrom').html('').select2().next().css('width', selectWidth);
      }, 0)
    },
    del: function (i) {
      b.days.splice(i, 1);
    },
    save: function () {
      var Period1 = [];
      var ProjectID1 = [];
      var JobContent1 = [];
      var JobResult1 = [];
      var i = 0;
      var o = [];
      var l = b.days.length;
      for (; i < l; i++) {
        if (!b.days[i].name) {
          alert('项目不能为空！');
          return false;
        }

        o.push({
          cost: b.days[i].cost,
          projectID: b.days[i].projectID,
          detail: b.days[i].detail,
          result: b.days[i].result
        });
      }
      if (b.dayForm.name && b.dayForm.cost) {
        o.push({
          cost: b.dayForm.cost,
          projectID: b.dayForm.projectID,
          detail: b.dayForm.detail,
          result: b.dayForm.result
        })
      }

      if (greatThan8(o) > 8) {
        alert('花费时间总计不能超过8小时！');
        return false;
      }

      i = 0;
      l = o.length;
      for (; i < l; i++) {
        Period1.push(o[i].cost);
        ProjectID1.push(o[i].projectID);
        JobContent1.push(o[i].detail);
        JobResult1.push(o[i].result);
      }

      var submitObj = {
        Period1: Period1.join('$D='),
        ReportDate: getUrlId(),
        ProjectID1: ProjectID1.join('$D='),
        JobContent1: JobContent1.join('$D='),
        JobResult1: JobResult1.join('$D='),
        JobResult2: b.form.value
      };

      // console.log(submitObj)
      if (!submitObj.ProjectID1) {
        alert('至少填写一条记录！');
        return false;
      }

      loading.show();
      $.ajax({
        url: '/api/CommonApi?API=ITSaveMyDaily',
        type: 'post',
        data: {
          ApiParamObj: JSON.stringify(submitObj)
        },
        dataType: 'json',
        success: function (data) {
          if (data.Success) {
            console.log(data);
            window.location.href = '/Dept/Project/level3';
          }
        }
      });
    }
  }
});

function resetDayForm() {
  return {
    projectID: '',
    name: '',
    detail: '',
    result: '',
    cost: ''
  };
}

function greatThan8(o) {
  var i = 0;
  var l = o.length;
  var allCost = 0;

  for (; i < l; i++) {

    if (o[i].cost) {
      allCost += parseFloat(o[i].cost);
    }

  }
  return allCost;
}

select2();
// 页面载入时读取数据
function getDayDetail() {

  var brand = getBrand();
  select2Event();

  $('#selectBrandForm').html(brand).select2().next().css('width', selectWidth);
  $('#selectProjectFrom').html('<option selected="selected">请选择</option>').select2().next().css('width', selectWidth);
  $.ajax({
    url: '/api/CommonApi?API=ITGetMyDailyByDay',
    type: 'get',
    data: {Day: getUrlId()},
    dataType: 'json',
    success: function (data) {
      if (data.Success) {
        loading.hide();
        var o = data.ApiParamObj;
        var obj = {};
        var i = 0;
        var l = o.length;
        if (o.length) {
          edit = true;
        } else {
          return false;
        }
        for (; i < l; i++) {
          if (!obj[o[i].LogType]) {
            obj[o[i].LogType] = [];
          }
          obj[o[i].LogType].push(o[i]);
        }
        // 每天8小时
        i = 0;
        o = obj['0_PERIOD_LOG'];
        l = o.length;

        for (; i < l; i++) {
          b.days.push({
            projectID: o[i].ProjectID,
            detail: o[i].JobContent,
            result: o[i].JobResult,
            cost: o[i].Period
          });
        }

        setTimeout(function () {
          i = 0;
          o = obj['0_PERIOD_LOG'];
          l = o.length;

          for (; i < l; i++) {
            eachProjectId(b.days, i, 'name', function (i, id) {
              var v = getProjectName(o[i].ProjectID);
              var h = setProjects(v);

              if (v) {
                $('#selectBrand' + i).html(brand).select2().val(v.BrandName).trigger('change').next().css('width', selectWidth);
                $('#selectProject' + i).html(h).select2().val(o[i].ProjectID).trigger('change').next().css('width', selectWidth);
              }

            });
          }

        }, 0);

        // 今日总结
        o = obj['2_SUMMARY_LOG'];

        Vue.set(b.form, 'value', o[0].JobResult);
        Vue.set(b.form, 'id', o[0].ProjectID);

      }
    }
  });
}

function setDayHours() {
  var i = 0;
  var step = 0.5;
  var e = 8;
  var arr = [];
  while (i < 8) {
    i = i + step;
    arr.push({
      value: i
    });
  }
  return arr;
}

// 获取所有品牌
function select2() {

  getAllBrandsAndProjects(function (data) {
    var obj = data.ApiParamObj;
    var key = {};
    var i = 0;
    var l = obj.length;
    for (; i < l; i++) {
      if (!key[obj[i].Key]) {
        key[obj[i].Key] = [];
      }
      key[obj[i].Key].push(obj[i]);
    }
    allBrand = key['BRAND'];
    allProject = key['PROJECT'];
    allProject = allProject ? allProject : [];

    getDayDetail();


  });
}

// 生成品牌选项
function getBrand() {
  var obj = allBrand;
  var i = 0;
  var l = obj.length;
  var specBrand1 = '';
  var specBrand2 = '';
  var optionsBrand0 = '<option value="" selected="selected">请选择</option>';
  var optionsBrand3 = '';
  for (; i < l; i++) {
    if (obj[i].BrandName) {
      if (obj[i].BrandName.indexOf('储吉') !== -1) {
        specBrand1 += '<option value="' + obj[i].BrandName + '">' + obj[i].BrandName + '</option>';
      } else if (obj[i].BrandName.indexOf('嵩瀚') !== -1) {
        specBrand2 += '<option value="' + obj[i].BrandName + '">' + obj[i].BrandName + '</option>';
      } else {
        optionsBrand3 += '<option value="' + obj[i].BrandName + '">' + obj[i].BrandName + '</option>';
      }

    }

  }
  return optionsBrand0 + specBrand1 + specBrand2 + optionsBrand3;
}

function select2Event() {
  // 8小时列表 项目选择统计联动
  $('#day').on('change', '.selectBrand', function () {
    var val = $(this).find(':selected').val();
    var optionsProject = '<option value="" selected="selected">请选择</option>';
    var i = 0;

    var l = allProject.length;
    for (; i < l; i++) {
      if (allProject[i]['BrandName'] === val) {
        optionsProject += '<option value="' + allProject[i].ProjectID + '">' + allProject[i].ProjectName + '</option>';
      }
    }
    $(this).parent().next().children('.selectProject').html(optionsProject).select2().next().css('width', selectWidth);

  });


  $('#day').on('change', 'select', function () {
    var selects = $('#day select');
    var obj = {};
    var selected;
    selects.each(function () {
      selected = $(this).find(':selected');
      var index = $(this).parentsUntil('tr').parent().index();
      var html = selected.html();
      var val = selected.val();
      var hasProject = $(this).hasClass('selectProject');
      if (hasProject) {
        if (index < b.days.length) {
          if (selected.val()) {
            obj[selected.val()] = html;
            b.days[index].name = html;
            b.days[index].projectID = val;


          } else {
            obj[selected.val()] = '';
            b.days[index].name = '';
            b.days[index].projectID = '';
          }
        } else if (index === b.days.length) {
          if (selected.val()) {
            Vue.set(b.dayForm, 'name', html);
            Vue.set(b.dayForm, 'projectID', val);
          } else {
            Vue.set(b.dayForm, 'name', '');
            Vue.set(b.dayForm, 'projectID', '');
          }

        }
      }
    });
    return false;

  });
}

function eachProjectId(obj, i, key, callback) {
  var j = 0;
  var k = allProject.length;
  var id = '';
  if (k) {
    for (; j < k; j++) {
      if ((allProject[j].ProjectName == obj[i][key]) && (allProject[j].ProjectID == obj[i].projectID)) {
        id = allProject[j].ProjectID;
        break;
      }
    }
    callback(i, id);
  }

}

function getProjectName(id) {
  var obj = allProject;
  var i = 0;
  var l = obj.length;
  for (; i < l; i++) {
    if (obj[i].ProjectID === id) {
      return obj[i];
    }
  }
}

function setProjects(t) {
  var obj = allProject;
  var i = 0;
  var l = obj.length;
  var h = '<option value="" selected="selected">请选择</option>';
  for (; i < l; i++) {
    if (obj[i].BrandName === t.BrandName) {
      h += '<option value="' + obj[i].ProjectID + '">' + obj[i].ProjectName + '</option>';
    }
  }
  return h;
}